package com.example.controller;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.example.dao.OrderDao;
import com.example.entity.Order;
import com.example.utils.PayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.Map;

@Controller
@RequestMapping("/api/alipay")
public class AliPayController {

    @Autowired
    private PayUtil payUtil;

    @Autowired
    private OrderDao orderDao; // 注入 OrderDao

    @PostMapping("/pay")
    public void alipay(
            @RequestParam Integer orderId,
            HttpServletResponse response
    ) throws AlipayApiException, IOException {
        // 1. 查询订单
        System.out.println("接收到的orderId: " + orderId);
        Order order = orderDao.findByOrderId(orderId);
        if (order == null) {
            System.out.println("数据库查询结果为空");
            response.sendError(404, "订单不存在");
            return;
        }

        // 2. 直接使用 Double 类型的 price，无需转换
        String html = payUtil.sendRequestToAlipay(
                orderId.toString(),
                order.getPrice(), // 直接传递 Double
                "食谱ID: " + order.getRecipeid()
        );

        // 3. 返回支付宝HTML
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(html);
        response.getWriter().flush();
    }

    @GetMapping("/return")
    public String returnCallback(
            @RequestParam String out_trade_no // 支付宝返回的订单号（String 类型）
    ) throws ParseException {
        // 1. 查询支付宝支付状态
        String queryResult = payUtil.query(out_trade_no);
        JSONObject jsonObject = JSONObject.parseObject(queryResult);
        Map<String, Object> responseMap = (Map) jsonObject.get("alipay_trade_query_response");

        // 2. 更新订单状态
        if ("TRADE_SUCCESS".equals(responseMap.get("trade_status"))) {
            Integer orderId = Integer.parseInt(out_trade_no); // 转换类型
            Order order = orderDao.findByOrderId(orderId);
            if (order != null) {
                order.setOrderstatus("completed"); // 更新状态为已完成
                orderDao.updateOrder(order); // 假设有更新方法
                return "redirect:/orderlist"; // 跳转到订单列表页
            }
        }
        return "redirect:/error"; // 失败跳转
    }

    @PostMapping("/notify")
    public String notifyCallback(@RequestParam String out_trade_no) {
        // 异步通知逻辑（同上）
        Integer orderId = Integer.parseInt(out_trade_no);
        Order order = orderDao.findByOrderId(orderId);
        if (order != null) {
            order.setOrderstatus("completed");
            orderDao.updateOrder(order);
        }
        return "success"; // 必须返回 success
    }
}